<?php

namespace Icsoc\DataBundle\Model;

use Elasticsearch\Client;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * 录音语音相关
 * Class RecordModel
 *
 * @package Icsoc\DataBundle\Model
 */
class RecordModel extends BaseModel
{
    /** @var ContainerInterface */
    public $container;

    /** @var \Doctrine\DBAL\Connection */
    private $dbal;

    /**
     * 录音呼叫类型
     *
     * @var array
     */
    private $rcalltype = array(
        '1' => '呼出',
        '2' => '呼入',
    );

    /**
     * 录音备份任务状态
     *
     * @var array
     */
    private $recordbatchcreat = array(
        '1' => '待生成',
        '2' => '正在生成',
        '3' => '已完成',
        '4' => '生成失败',
    );

    /**
     * RecordModel constructor.
     *
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->dbal = $container->get('doctrine.dbal.default_connection');
    }

    /**
     * 获取录音数据
     *
     * @param array $param
     *
     * @return array
     */
    public function getRecordListFromElasticsearch(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $big = empty($param['big']) ? false : $param['big'];
        $info = empty($param['info']) ? '' : $this->purifyHtml($param['info']);
        $endResult = $this->container->getParameter("end_type");
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        $evaluates = $this->container->getParameter('EVALUATES');
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 403, 'message' => 'info格式非json');
            }
        }

        $rows = empty($addInfo['pagination']['rows']) ? 10 : $addInfo['pagination']['rows'];
        $page = empty($addInfo['pagination']['page']) ? 1 : $addInfo['pagination']['page'];
        $order = empty($addInfo['sort']['order']) ? 'desc' : $addInfo['sort']['order'];
        $field = empty($addInfo['sort']['field']) ? 'id' : $addInfo['sort']['field'];
        $type = "win_agcdr";
        $condition = array(
            'fixup' => array(
                'index' => 'agcdr',
                'type' => $type,
                'rows' => $rows == -1 ? 1000 : $rows,
                'page' => $page,
                'order' => $order,
                'field' => $field,
            ),
            'term' => array('vcc_id' => array('type' => 'match', 'value' => $vccId)),
        );
        $startTime = isset($addInfo['filter']['start_time']) ? $addInfo['filter']['start_time'] : date('Y-m-d');
        $endTime = isset($addInfo['filter']['end_time']) ? $addInfo['filter']['end_time'] : date('Y-m-d').' 23:59:59';
        $time = $this->container->get("icsoc_core.common.class")->rolesCanSearchAllReportDatas($startTime, $endTime, 'date');
        if ($time == 'no') {
            $condition['term']['vcc_id'] = array('type' => 'match', 'value' => 0);
        }

        if (isset($addInfo['filter'])) {
            //坐席工号；
            if (!empty($addInfo['filter']['ag_num']) && $addInfo['filter']['ag_num'] != '-1') {
                $agId = (int) $addInfo['filter']['ag_num'];
                $condition['term']['ag_id'] = array('type' => 'match', 'value' => $agId);
            }
            //呼叫类型
            if (isset($addInfo['filter']['call_type']) && !empty($addInfo['filter']['call_type'])) {
                $callType = (int) $addInfo['filter']['call_type'];
                if ($callType == 1) {
                    $condition['term']['call_type'] = array('type' => 'should', 'value' => '1,3,5');
                } elseif ($callType == 2) {
                    //12  转电话  11转内线
                    $condition['term']['call_type'] = array('type' => 'should', 'value' => '2,4,6,11,12');
                }
            }

            //坐席号码
            if (isset($addInfo['filter']['ag_phone']) && !empty($addInfo['filter']['ag_phone'])) {
                $condition['term']['ag_phone'] = array('type' => 'wildcard', 'value' => $addInfo['filter']['ag_phone']);
            }

            //客户号码
            if (isset($addInfo['filter']['cus_phone']) && !empty($addInfo['filter']['cus_phone'])) {
                $condition['term']['cus_phone'] = array('type' => 'wildcard', 'value' => $addInfo['filter']['cus_phone']);
            }

            //开始时间
            if (isset($addInfo['filter']['start_time']) && !empty($addInfo['filter']['start_time'])) {
                $startTime = $addInfo['filter']['start_time'];
                if (isset($time['startTime'])) {
                    $startTime = $time['startTime'];
                }
                $msg = $this->container->get('icsoc_data.helper')->isDateTime('开始时间格式不正确', $startTime, 404);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }

                $condition['term']['start_time'] = array('type' => 'range', 'value' => strtotime($startTime), 'field' => 'start_time', 'operation' => 'gte');
            }

            //结束时间
            if (isset($addInfo['filter']['end_time']) && !empty($addInfo['filter']['end_time'])) {
                $endTime = $addInfo['filter']['end_time'];
                if (isset($time['endTime'])) {
                    $endTime = $time['endTime'];
                }
                $msg = $this->container->get('icsoc_data.helper')->isDateTime('结束时间格式不正确', $endTime, 405);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }

                $condition['term']['end_time'] = array('type' => 'range', 'value' => strtotime($endTime), 'field' => 'start_time', 'operation' => 'lte');
            }

            //时长小于
            if (isset($addInfo['filter']['esecs']) && !empty($addInfo['filter']['esecs'])) {
                $esecs = (int) $addInfo['filter']['esecs'];
                $condition['term']['esecs'] = array('type' => 'range', 'value' => $esecs, 'field' => 'conn_secs', 'operation' => 'lte');
            }

            //时长大于
            if (isset($addInfo['filter']['ssecs']) && !empty($addInfo['filter']['ssecs'])) {
                $ssecs = (int) $addInfo['filter']['ssecs'];
                $condition['term']['ssecs'] = array('type' => 'range', 'value' => $ssecs, 'field' => 'conn_secs', 'operation' => 'gte');
            }

            //技能组id
            if (isset($addInfo['filter']['que_id']) && $addInfo['filter']['que_id'] != '-1') {
                $queId = (int) $addInfo['filter']['que_id'];
                $condition['term']['que_id'] = array('type' => 'match', 'value' => $queId);
            }
            //结束类型
            if (isset($addInfo['filter']['end_result']) && !empty($addInfo['filter']['end_result'])) {
                $condition['term']['endresult'] = array('type' => 'match', 'value' => $addInfo['filter']['end_result']);
            }
            //评价结果
            if (isset($addInfo['filter']['evaluates'])) {
                $evaluate = (int) $addInfo['filter']['evaluates'];
                $condition['term']['evaluate'] = array('type' => 'match', 'value' => $evaluate);
            }
            if (isset($addInfo['filter']['id']) && $addInfo['filter']['id'] !== false) {
                $condition['term']['id'] = array('type' => 'should', 'value' => $addInfo['filter']['id']);
            }

            if (isset($addInfo['filter']['group_id']) && $addInfo['filter']['group_id'] != '-1') {
                $condition['term']['group_id'] = array('type' => 'match', 'value' => $addInfo['filter']['group_id']);
            }

            //中继号码
            if (isset($addInfo['filter']['serv_num']) && !empty($addInfo['filter']['serv_num'])) {
                $condition['term']['serv_num'] = array('type' => 'match', 'value' => $addInfo['filter']['serv_num']);
            }
        }

        $authority = $this->container->get("icsoc_core.common.class")->getAuthorityConditionForElasearch('ag_id', 'que_id', 1);
        if ($authority === false) {
            return array(
                'code' => 404,
                'message' => '权限内无任何数据',
            );
        } else {
            if (!empty($authority['ag_id']) && $addInfo['filter']['ag_num'] == '-1') {
                $condition['term']['ag_id'] = array('type' => 'terms', 'value' => $authority['ag_id']);
            }
            if (!empty($authority['que_id']) && $addInfo['filter']['que_id'] == '-1') {
                $condition['term']['que_id'] = array('type' => 'terms', 'value' => $authority['que_id']);
            }
            if (!empty($authority['group_id']) && $addInfo['filter']['group_id'] == '-1') {
                $condition['term']['group_id'] = array('type' => 'terms', 'value' => $authority['group_id']);
            }
        }
        $cusPhoneAuthority = $this->container->get("icsoc_core.common.class")->getWhetherHaveAuthority('icsoc_show_cus_phone');
        $condition['term']['record_mark'] = array('type' => 'match', 'value' => 1);
        $condition['export'] = empty($addInfo['export']) ? 0 : 1;
        //如果是异步导出
        if ($big == true) {
            $esSearch['code'] = 200;
            $esSearch['data'] = $this->container->get('icsoc_data.model.record')->getEsSearch($condition);

            return $esSearch;
        }

        $rows = $this->container->get('icsoc_data.model.report')->getDataFromESAndMongo($condition, 'win_agcdr');
        $resultData = $rows['data'];
        $count = $rows['count'];
        $totalPages = $rows['totalPages'];

        $agNicknames = $this->dbal->fetchAll(
            "SELECT id,ag_nickname FROM win_agent WHERE vcc_id = :vcc_id ",
            array('vcc_id' => $vccId)
        );
        $nicknameInfo = array();
        foreach ($agNicknames as $k => $v) {
            $nicknameInfo[$v['id']] = $v['ag_nickname'];
        }

        $result = array();
        foreach ($resultData as $k => $v) {
            $result[$k]['id'] = (string) $v['_id'];
            $result[$k]['serv_num'] = $v['serv_num'];
            $result[$k]['ag_id'] = $v['ag_id'];
            $result[$k]['agcdr_id'] = isset($v['agcdr_id']) ? (string) $v['agcdr_id'] : '';
            $result[$k]['ag_phone'] = $v['ag_phone'];
            $result[$k]['cus_phone'] = $this->container->get("icsoc_core.common.class")->concealCusPhone($v['cus_phone'], $cusPhoneAuthority);
            $result[$k]['que_name'] = $v['que_name'];
            $result[$k]['record_file'] = $v['record_file'];
            $result[$k]['conn_secs'] = $v['conn_secs'];
            $result[$k]['ag_num'] = $v['ag_num'];
            $result[$k]['ag_name'] = $v['ag_name'];
            $result[$k]['ag_nickname'] = !empty($nicknameInfo[$v['ag_id']]) ? $nicknameInfo[$v['ag_id']] : '';
            $result[$k]['call_id'] = (string) $v['call_id'];
            $result[$k]['group_name'] = $v['group_name'];
            $result[$k]['start_time'] = $v['start_time'] ? date("Y-m-d H:i:s", $v['start_time']) : "";
            $result[$k]['end_time'] = $v['end_time'] ? date("Y-m-d H:i:s", $v['end_time']) : "";
            if ($v['call_type'] == 1 || $v['call_type'] == 3 || $v['call_type'] == 5) {
                $result[$k]['call_type'] = $this->rcalltype[1]; // out
            } else {
                $result[$k]['call_type'] = $this->rcalltype[2]; // in
            }
            $result[$k]['evaluate'] = isset($evaluates[$v['evaluate']]) ? $evaluates[$v['evaluate']] : '';
            $result[$k]['endresult'] = isset($endResult[$v['endresult']]) ?
                $endResult[$v['endresult']] : '其它';
            unset($rows[$k]);
        }
        unset($resultData);

        return array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'data' => $result,
            'totalPage' => $totalPages,
            'page' => $page,
        );
    }

    /**
     * 从elasticsearch中获取数据
     *
     * @param array $condition
     *
     * @return array
     */
    public function searchData(array $condition)
    {
        $index = isset($condition['fixup']['index']) ? $condition['fixup']['index'] : '';
        $esType = isset($condition['fixup']['type']) ? $condition['fixup']['type'] : '';
        $rows = isset($condition['fixup']['rows']) ? $condition['fixup']['rows'] : 10;
        $page = isset($condition['fixup']['page']) ? $condition['fixup']['page'] : 1;
        $field = isset($condition['fixup']['field']) ? $condition['fixup']['field'] : 'id';
        $order = isset($condition['fixup']['order']) ? $condition['fixup']['order'] : 'desc';
        $export = isset($condition['export']) ? $condition['export'] : '';
        $from = $rows * $page - $rows;
        $from = $from > 0 ? $from : 0;
        $query = array(
            'query' => array(),
        );
        if (is_array($field)) {
            foreach ($field as $f) {
                $query['sort'][] = array($f => array('order' => $order, 'unmapped_type' => 'date'));
            }
        } else {
            $query['sort'] = array($field => array('order' => $order, 'unmapped_type' => 'date'));
        }

        $terms = $condition['term'];
        foreach ($terms as $k => $v) {
            switch ($v['type']) {
                case 'range':
                    $query['query']['bool']['must'][] = array('range' => array($v['field'] => array($v['operation'] => $v['value'])));
                    break;
                case 'match':
                    $query['query']['bool']['must'][] = array('match' => array($k => $v['value']));
                    break;
                case 'nomatch':
                    $query['query']['bool']['must_not'][] = array('match' => array($k => $v['value']));
                    break;
                case 'wildcard':
                    if (!isset($v['bool'])) {
                        $query['query']['bool']['must'][] = array('wildcard' => array($k => "*{$v['value']}*"));
                    } else {
                        $query['query']['bool']['must'][] = array('bool' => array($v['operation'] => array(array('wildcard' => array($k => "*{$v['value']}*")), array('match' => array($v['field'] => array('query' => $v['value'], 'operator' => 'and'))))));
                    }
                    break;
                case 'terms':
                    $query['query']['bool']['must'][] = array('terms' => array($k => $v['value']));
                    break;
                case 'should':
                    $values = explode(',', $v['value']);
                    foreach ($values as $val) {
                        $query['query']['bool']['should'][] = array('match' => array($k => $val));
                    }
                    $query['query']['bool']['minimum_should_match'] = 1;//至少匹配一个
                    break;
                case 'or':
                    if (isset($v['columns'])) {
                        foreach ($v['columns'] as $column) {
                            $query['query']['bool']['should'][] = array('wildcard' => array($column => "*{$v['value']}*"));
                        }
                    }
                    $query['query']['bool']['minimum_should_match'] = 1;//至少匹配一个
                    break;
                case 'multiNomatch':
                    if (isset($v['multi'])) {
                        foreach ($v['value'] as $value) {
                            $query['query']['bool']['must_not'][] = array('match' => array($k => $value));
                        }
                    }
                    break;
            }
        }

        $params = array(
            "size" => $rows,
            "from" => $from,
            'index' => $index,
            'type' => $esType,
            'body' => $query,
        );

        if (!empty($export)) {
            $params['size'] = 10000;
            $params['search_type'] = 'scan';
            $params['scroll'] = '30s';
        }
        $sources = array();
        $total = 10;

        try {
            $hosts = $this->container->getParameter('elasticsearch_hosts');
            $client = new Client(array('hosts' => $hosts));
            $result = $client->search($params);
            if (!empty($export)) {
                $scrollId = $result['_scroll_id'];
                while (true) {
                    $response = $client->scroll(
                        array(
                            "scroll_id" => $scrollId,
                            "scroll" => "30s",
                        )
                    );

                    if (count($response['hits']['hits']) > 0) {
                        $sources = array_merge($sources, $response['hits']['hits']);
                        $total = $response['hits']['total'];
                        $scrollId = $response['_scroll_id'];
                    } else {
                        break;
                    }
                }
            } else {
                $sources = $result['hits']['hits'];
                $total = $result['hits']['total'];
            }
        } catch (\Exception $e) {
            $logger = $this->container->get('logger');
            $logger->error($e->getMessage());

            return array(
                'code' => 500,
                'message' => '发生异常',
                'total' => 0,
                'page' => 0,
                'total_pages' => 0,
                'data' => array(),
            );
        }

        $data = array();
        foreach ($sources as $source) {
            $data[] = $source['_source'];
        }

        return array(
            'code' => 200,
            'message' => 'ok',
            'total' => ceil($total / $rows),
            'count' => $total,
            'page' => $page,
            'data' => $data,
        );
    }

    /**
     * 异步导出 处理查询es的条件数组
     *
     * @param array $condition
     *
     * @return array
     */
    public function getEsSearch(array $condition)
    {
        $index = isset($condition['fixup']['index']) ? $condition['fixup']['index'] : '';
        $esType = isset($condition['fixup']['type']) ? $condition['fixup']['type'] : '';
        $field = isset($condition['fixup']['field']) ? $condition['fixup']['field'] : 'start_time';
        $order = isset($condition['fixup']['order']) ? $condition['fixup']['order'] : 'desc';
        $query = array(
            'query' => array(),
        );
        if (isset($condition['fixup']['size'])) {
            $query['size'] = $condition['fixup']['size'];
        }
        if (is_array($field)) {
            foreach ($field as $f) {
                $query['sort'][] = array($f => array('order' => $order, 'unmapped_type' => 'date'));
            }
        } else {
            $query['sort'] = array($field => array('order' => $order, 'unmapped_type' => 'date'));
        }

        $terms = $condition['term'];
        foreach ($terms as $k => $v) {
            switch ($v['type']) {
                case 'range':
                    $query['query']['bool']['must'][] = array('range' => array($v['field'] => array($v['operation'] => $v['value'])));
                    break;
                case 'match':
                    $query['query']['bool']['must'][] = array('match' => array($k => $v['value']));
                    break;
                case 'nomatch':
                    $query['query']['bool']['must_not'][] = array('match' => array($k => $v['value']));
                    break;
                case 'wildcard':
                    if (!isset($v['bool'])) {
                        $query['query']['bool']['must'][] = array('wildcard' => array($k => "*{$v['value']}*"));
                    } else {
                        $query['query']['bool']['must'][] = array('bool' => array($v['operation'] => array(array('wildcard' => array($k => "*{$v['value']}*")), array('match' => array($v['field'] => array('query' => $v['value'], 'operator' => 'and'))))));
                    }
                    break;
                case 'terms':
                    $query['query']['bool']['must'][] = array('terms' => array($k => $v['value']));
                    break;
                case 'should':
                    $values = explode(',', $v['value']);
                    foreach ($values as $val) {
                        $query['query']['bool']['should'][] = array('match' => array($k => $val));
                    }
                    $query['query']['bool']['minimum_should_match'] = 1;//至少匹配一个
                    break;
                case 'or':
                    $query['query']['bool']['should'][] = array('match' => array($k => $v['value']));
                    break;
            }
        }
        if (isset($condition['aggs']) && !empty($condition['aggs'])) {
            $query['aggs'] = $condition['aggs'];
        }

        $params = array(
            'index' => $index,
            'type' => $esType,
            'body' => $query,
        );

        return $params;
    }

    /**
     * 直接获取ES中的数据数量
     *
     * @param array $condition
     *
     * @return array
     */
    public function getEsCount(array $condition)
    {
        $index = isset($condition['fixup']['index']) ? $condition['fixup']['index'] : '';
        $esType = isset($condition['fixup']['type']) ? $condition['fixup']['type'] : '';
        $query = array(
            'query' => array(),
            'size' => (int) 0,
        );

        $other = $condition;
        unset($other['term']);
        unset($other['fixup']);

        $terms = $condition['term'];
        foreach ($terms as $k => $v) {
            switch ($v['type']) {
                case 'range':
                    $query['query']['bool']['must'][] = array('range' => array($v['field'] => array($v['operation'] => $v['value'])));
                    break;
                case 'match':
                    $query['query']['bool']['must'][] = array('match' => array($k => $v['value']));
                    break;
                case 'nomatch':
                    $query['query']['bool']['must_not'][] = array('match' => array($k => $v['value']));
                    break;
                case 'wildcard':
                    if (!isset($v['bool'])) {
                        $query['query']['bool']['must'][] = array('wildcard' => array($k => "*{$v['value']}*"));
                    } else {
                        $query['query']['bool']['must'][] = array('bool' => array($v['operation'] => array(array('wildcard' => array($k => "*{$v['value']}*")), array('match' => array($v['field'] => array('query' => $v['value'], 'operator' => 'and'))))));
                    }
                    break;
                case 'terms':
                    $query['query']['bool']['must'][] = array('terms' => array($k => $v['value']));
                    break;
                case 'should':
                    $values = explode(',', $v['value']);
                    foreach ($values as $val) {
                        $query['query']['bool']['should'][] = array('match' => array($k => $val));
                    }
                    $query['query']['bool']['minimum_should_match'] = 1;//至少匹配一个
                    break;
                case 'or':
                    $query['query']['bool']['should'][] = array('match' => array($k => $v['value']));
            }
        }
        if (!empty($other)) {
            $query = array_merge($query, $other);
        }
        $params = array(
            'index' => $index,
            'type' => $esType,
            'body' => $query,
        );
        try {
            $hosts = $this->container->getParameter('elasticsearch_hosts');
            $client = new Client(array('hosts' => $hosts));
            $result = $client->search($params);
            $count = $result['hits']['total'];
        } catch (\Exception $e) {
            $logger = $this->container->get('logger');
            $logger->error($e->getMessage());

            return array(
                'code' => 500,
                'message' => '发生异常',
                'count' => 0,
            );
        }

        return array(
            'code' => 200,
            'message' => 'ok',
            'count' => $count,
            'data' => $result,
        );
    }

    /**
     * 录音列表
     *
     * @param array $param 参数，格式为
     *                     array(
     *                         vcc_code,//企业代码
     *                         info,// array 提供分页信息
     *                     )
     *
     * @return array
     */
    public function recordList(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $info = empty($param['info']) ? '' : $this->purifyHtml($param['info']);
        $endResult = $this->container->getParameter("end_type");
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        $evaluates = $this->container->getParameter('EVALUATES');
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 403, 'message' => 'info格式非json');
            }
        }
        $where = '';
        $params = array();
        if (isset($addInfo['filter'])) {
            //坐席工号；
            $where = isset($addInfo['filter']['ag_num']) && !empty($addInfo['filter']['ag_num']) ?
                " AND (ag_num LIKE '%".$addInfo['filter']['ag_num']."%' OR ag_name like '%".$addInfo['filter']['ag_num']."%') " : '';
            //呼叫类型
            if (isset($addInfo['filter']['call_type']) && !empty($addInfo['filter']['call_type'])) {
                $callType = (int) $addInfo['filter']['call_type'];
                if ($callType == 1) {
                    $where .= " AND (call_type = '1' OR call_type = '3' OR call_type = '5') ";
                } elseif ($callType == 2) {
                    $where .= " AND (call_type = '2' OR call_type = '4' OR call_type = '6') ";
                }
            }

            //坐席号码
            $where .= isset($addInfo['filter']['ag_phone']) && !empty($addInfo['filter']['ag_phone']) ?
                " AND ag_phone LIKE '%".$addInfo['filter']['ag_phone']."%' " : '';

            //客户号码
            $where .= isset($addInfo['filter']['cus_phone']) && !empty($addInfo['filter']['cus_phone']) ?
                " AND cus_phone LIKE '%".$addInfo['filter']['cus_phone']."%' " : '';

            //开始时间
            if (isset($addInfo['filter']['start_time']) && !empty($addInfo['filter']['start_time'])) {
                $startTime = $addInfo['filter']['start_time'];
                $msg = $this->container->get('icsoc_data.helper')->isDateTime('开始时间格式不正确', $startTime, 404);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $where .= " AND start_time >= UNIX_TIMESTAMP('$startTime')";
            }

            //结束时间
            if (isset($addInfo['filter']['end_time']) && !empty($addInfo['filter']['end_time'])) {
                $endTime = $addInfo['filter']['end_time'];
                $msg = $this->container->get('icsoc_data.helper')->isDateTime('结束时间格式不正确', $endTime, 405);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $where .= " AND start_time <= UNIX_TIMESTAMP('$endTime')";
            }

            //时长大于
            if (isset($addInfo['filter']['ssecs']) && !empty($addInfo['filter']['ssecs'])) {
                $where .= " AND conn_secs >= :ssecs ";
                $params['ssecs'] = $addInfo['filter']['ssecs'];
            }

            //时长小于
            if (isset($addInfo['filter']['esecs']) && !empty($addInfo['filter']['esecs'])) {
                $where .= " AND conn_secs <= :esecs ";
                $params['esecs'] = $addInfo['filter']['esecs'];
            }

            //技能组id
            if (isset($addInfo['filter']['que_id']) && !empty($addInfo['filter']['que_id'])) {
                $where .= " AND que_id = :que_id ";
                $params['que_id'] = $addInfo['filter']['que_id'];
            }
            //结束类型
            if (isset($addInfo['filter']['end_result']) && !empty($addInfo['filter']['end_result'])) {
                $where .= " AND endresult = :end_result ";
                $params['end_result'] = (int) $addInfo['filter']['end_result'];
            }
            //评价结果
            if (isset($addInfo['filter']['evaluates']) && $addInfo['filter']['evaluates'] !== false) {
                $where .= " AND evaluate = :evaluate ";
                $params['evaluate'] = (int) $addInfo['filter']['evaluates'];
            }
            if (isset($addInfo['filter']['id']) && $addInfo['filter']['id'] !== false) {
                $where .= " AND id IN (".$addInfo['filter']['id'].")";
            }

            if (isset($addInfo['filter']['group_id']) && $addInfo['filter']['group_id'] != '-1') {
                $where .= " AND group_id = {$addInfo['filter']['group_id']} ";
            }
            //中继号码
            if (isset($addInfo['filter']['serv_num']) && !empty($addInfo['filter']['serv_num'])) {
                $where .= " AND serv_num = :serv_num";
                $params['serv_num'] = $addInfo['filter']['serv_num'];
            }
        }

        /** @var  $authority (获取数据权限) */
        $authority = $this->container->get("icsoc_core.common.class")->getAuthorityCondition('ag_id', 'que_id', 1);
        if ($authority === false) {
            return array(
                'code' => 404,
                'message' => '权限内无任何数据',
            );
        } else {
            $where .= $authority.' ';
        }

        $params['vcc_id'] = $vccId;
        $params['record_mark'] = 1;

        $adsDbal = $this->container->get('doctrine.dbal.ads_connection');
        $count = $adsDbal->fetchColumn(
            'SELECT count(*) FROM win_agcdr WHERE vcc_id = :vcc_id AND record_mark = :record_mark '.$where,
            $params
        );
        /*$page = $this->container->get("icsoc_data.helper")->getPageInfo($count, 'win_agcdr', $addInfo);

        if (empty($addInfo['export'])) {
            $rows = $adsDbal->fetchAll(
                "SELECT id,ag_id,group_id,ag_name,ag_num,que_name,call_type,call_id,serv_num,ag_phone,cus_phone,start_time,end_time,conn_secs,record_file,endresult,evaluate ".
                "FROM win_agcdr ".
                "WHERE vcc_id = :vcc_id AND record_mark = :record_mark ".$where.
                'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
                $params
            );
        } else {
            $rows = $adsDbal->fetchAll(
                "SELECT id,ag_id,group_id,ag_name,ag_num,que_name,call_type,call_id,serv_num,ag_phone,cus_phone,start_time,end_time,conn_secs,record_file,endresult,evaluate ".
                "FROM win_agcdr ".
                "WHERE vcc_id = :vcc_id AND record_mark = :record_mark ".$where.
                'ORDER BY '.$page['sort'].' '.$page['order'],
                $params
            );
        }*/
        $forPageParam = $this->container->get('icsoc_data.model.report')->pageForAdsSearch($param['forPageParam'], $addInfo['pagination']['rows'], $count);
        $where .= $forPageParam['where'];
        $orderBy = $forPageParam['orderBy'];
        $sqlLimit = $forPageParam['sqlLimit'];
        $isReversed = $forPageParam['isReversed'];
        $isChangeRowlist = $forPageParam['isChangeRowlist'];
        $totalPage = $forPageParam['totalPage'];

        if (empty($addInfo['export'])) {
            $rows = $adsDbal->fetchAll(
                "SELECT id,ag_id,group_id,ag_name,ag_num,que_name,call_type,call_id,agcdr_id,serv_num,ag_phone,
                cus_phone,start_time,end_time,conn_secs,record_file,endresult,evaluate ".
                "FROM win_agcdr ".
                "WHERE vcc_id = :vcc_id AND record_mark = :record_mark ".$where.
                $orderBy.$sqlLimit,
                $params
            );
        } else {
            $rows = $adsDbal->fetchAll(
                "SELECT id,ag_id,group_id,ag_name,ag_num,que_name,call_type,call_id,agcdr_id,serv_num,ag_phone,
                cus_phone,start_time,end_time,conn_secs,record_file,endresult,evaluate ".
                "FROM win_agcdr ".
                "WHERE vcc_id = :vcc_id AND record_mark = :record_mark ".$where.
                $orderBy,
                $params
            );
        }

        $agNicknames = $this->dbal->fetchAll(
            "SELECT id,ag_nickname FROM win_agent WHERE vcc_id = :vcc_id ",
            array('vcc_id' => $vccId)
        );
        $nicknameInfo = array();
        foreach ($agNicknames as $k => $v) {
            $nicknameInfo[$v['id']] = $v['ag_nickname'];
        }

        $result = array();
        if ($isReversed == true) {
            $rows = array_reverse($rows);
        }

        foreach ($rows as $k => $v) {
            $result[$k]['server_num'] = $v['serv_num'];
            $result[$k]['ag_id'] = $v['ag_id'];
            $result[$k]['id'] = $v['id'];
            $result[$k]['ag_phone'] = $v['ag_phone'];
            $result[$k]['cus_phone'] = $v['cus_phone'];
            $result[$k]['que_name'] = $v['que_name'];
            $result[$k]['record_file'] = $v['record_file'];
            $result[$k]['conn_secs'] = $v['conn_secs'];
            //$result[$k]['ag_num'] = $v['ag_name']." ".$v['ag_num'];
            $result[$k]['ag_num'] = $v['ag_num'];
            $result[$k]['ag_name'] = $v['ag_name'];
            $result[$k]['ag_nickname'] = !empty($nicknameInfo[$v['ag_id']]) ? $nicknameInfo[$v['ag_id']] : '';
            $result[$k]['call_id'] = $v['call_id'];
            $result[$k]['agcdr_id'] = $v['agcdr_id'];
            $result[$k]['group_id'] = $v['group_id'];
            $result[$k]['start_time'] = $v['start_time'] ? date("Y-m-d H:i:s", $v['start_time']) : "";
            $result[$k]['end_time'] = $v['end_time'] ? date("Y-m-d H:i:s", $v['end_time']) : "";
            if ($v['call_type'] == 1 || $v['call_type'] == 3 || $v['call_type'] == 5) {
                $result[$k]['call_type'] = $this->RCALLTYPE[1]; // out
            } else {
                $result[$k]['call_type'] = $this->RCALLTYPE[2]; // in
            }
            $result[$k]['evaluate'] = isset($evaluates[$v['evaluate']]) ? $evaluates[$v['evaluate']] : '';
            $result[$k]['endresult'] = isset($endResult[$v['endresult']]) ?
                $endResult[$v['endresult']] : '其它';
        }

        return array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'data' => $result,
            'totalPage' => $totalPage,
            'isChangeRowlist' => $isChangeRowlist,
        );
    }

    /**
     * 留言列表
     *
     * @param array $param 参数，格式为
     *                     array(
     *                         vcc_code,//企业代码
     *                         info,// array 提供分页信息
     *                     )
     *
     * @return array
     */
    public function voiceList(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $info = empty($param['info']) ? '' : $this->purifyHtml($param['info']);
        $big = $param['big'];
//        $win_ip = $this->container->getParameter('win_ip');
//        $win_web_port = $this->container->getParameter('win_web_port');
//        $win_system_name = $this->container->getParameter('win_system_name');

        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 403, 'message' => 'info格式非json');
            }
        }
        $where = '';
        $params = array();
        if (isset($addInfo['filter'])) {
            //主叫号码；
            $where .= isset($addInfo['filter']['caller']) && !empty($addInfo['filter']['caller']) ?
                " AND caller LIKE '%".$addInfo['filter']['caller']."%' " : '';

            //被叫号码
            $where .= isset($addInfo['filter']['called']) && !empty($addInfo['filter']['called']) ?
                " AND called LIKE '%".$addInfo['filter']['called']."%' " : '';

            //是否已收听
            if (isset($addInfo['filter']['listen_mark']) && $addInfo['filter']['listen_mark'] !== false) {
                $listenMark = $addInfo['filter']['listen_mark'];
                $where .= " AND listen_mark = :listen_mark ";
                $params['listen_mark'] = $listenMark;
            }

            //是否已下载
            if (isset($addInfo['filter']['down_mark']) && $addInfo['filter']['down_mark'] !== false) {
                $downMark = $addInfo['filter']['down_mark'];
                $where .= " AND down_mark = :down_mark ";
                $params['down_mark'] = $downMark;
            }

            //开始时间
            if (isset($addInfo['filter']['start_time']) && !empty($addInfo['filter']['start_time'])) {
                $startTime = $addInfo['filter']['start_time'];
                $msg = $this->container->get('icsoc_data.helper')->isDateTime('开始时间格式不正确', $startTime, 404);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $where .= "AND start_time >= UNIX_TIMESTAMP('$startTime')";
            }

            //结束时间
            if (isset($addInfo['filter']['end_time']) && !empty($addInfo['filter']['end_time'])) {
                $endTime = $addInfo['filter']['end_time'];
                $msg = $this->container->get('icsoc_data.helper')->isDateTime('结束时间格式不正确', $endTime, 405);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $where .= "AND start_time <= UNIX_TIMESTAMP('$endTime')";
            }

            //时长大于
            if (isset($addInfo['filter']['ssecs']) && !empty($addInfo['filter']['ssecs'])) {
                $where .= " AND rec_secs >= :ssecs ";
                $params['ssecs'] = $addInfo['filter']['ssecs'];
            }

            //时长小于
            if (isset($addInfo['filter']['esecs']) && !empty($addInfo['filter']['esecs'])) {
                $where .= " AND rec_secs <= :esecs ";
                $params['esecs'] = $addInfo['filter']['esecs'];
            }
        }

        $params['vcc_id'] = $vccId;
        $count = $this->container->get('doctrine.dbal.cdr_connection')->fetchColumn(
            'SELECT count(*) 
            FROM win_voicemail 
            WHERE vcc_id = :vcc_id '.$where,
            $params
        );
        $page = $this->container->get("icsoc_data.helper")->getPageInfo($count, 'win_voicemail', $addInfo);
        if (empty($addInfo['export'])) {
            $list = $this->container->get('doctrine.dbal.cdr_connection')->fetchAll(
                "SELECT id,caller,called,start_time,rec_secs,rec_file,listen_mark,down_mark 
                FROM win_voicemail 
                WHERE vcc_id = :vcc_id ".$where.'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
                $params
            );
        } else if(!empty($addInfo['export']) && $big == false) {
            $list = $this->container->get('doctrine.dbal.cdr_connection')->fetchAll(
                "SELECT id,caller,called,start_time,rec_secs,rec_file,listen_mark,down_mark 
                FROM win_voicemail 
                WHERE vcc_id = :vcc_id ".$where.'ORDER BY '.$page['sort'].' '.$page['order'],
                $params
            );
        } else {
            /** 最大的ID **/
            $maxId = $this->dbal->fetchColumn(
                'SELECT MAX(id) FROM win_voicemail '
            );
            $list = $this->container->get('icsoc_data.model.export')->interpolateQuery(
                "SELECT id,caller,called,start_time,rec_secs,rec_file,listen_mark,down_mark 
                FROM win_voicemail AS wv INNER JOIN(
                SELECT id from win_voicemail 
                WHERE vcc_id = :vcc_id ".$where." 
                AND id <= '".$maxId."'".'
                ORDER BY '.$page['sort'].' '.$page['order'].' %LIMIT%) AS wv2 USING (id)',
                $params
            );

            return array(
                'code' => 200,
                'message' => 'ok',
                'total' => $count,
                'sql' => $list,
            );
        }
        $cusPhoneAuthority = $this->container->get("icsoc_core.common.class")->getWhetherHaveAuthority('icsoc_show_cus_phone');
        $result = array();
        foreach ($list as $k => $v) {
            $result[$k] = $v;
            $result[$k]['start_time'] = date("Y-m-d H:i:s", $v['start_time']);
            $result[$k]['listen_mark'] = $v['listen_mark'] == 1 ? "已收听" : "未收听";
            $result[$k]['down_mark'] = $v['down_mark'] == 1 ? "已下载" : "未下载";
            $result[$k]['caller'] = $this->container->get("icsoc_core.common.class")->concealCusPhone($v['caller'], $cusPhoneAuthority);
        }

        return array('code' => 200, 'message' => 'ok', 'total' => $count, 'data' => $result, 'totalPage' => $page['totalPage']);
    }

    /**
     * 批量打包
     *
     * @param array $params
     *
     * @return array|string
     */
    public function zipDownRecord(array $params)
    {
        $list = $this->getRecordListFromElasticsearch($params);
        if (isset($list['code']) && $list['code'] == 200) {
            //批量处理打包
            if (empty($list['data'])) {
                return array('code' => '407', 'message' => '没有数据');
            }

            $file = '/tmp/'.date("YmdHis").$params['vcc_code'].'.zip';
            $command = "zip -r ".$file.' ';
            $tmpDir = "/tmp/".$params['vcc_code'].time().rand();
            @mkdir($tmpDir);
            //把文件移动到临时文件中
            foreach ($list['data'] as $data) {
                $recordUrl = $this->processRecordUrl($data['record_file']);
                if ($recordUrl !== false && !empty($recordUrl)) {
                    $data = $this->readRemoteFile($recordUrl);
                    $newTmpDir = $tmpDir.'/'.basename(substr($recordUrl,strrpos($recordUrl, '/')+1));
                    $handle = fopen($newTmpDir, 'w');
                    fwrite($handle, $data);
                    fclose($handle);
                }
            }
            @exec($command.$tmpDir); //压缩文件夹；
            //在删除文件；
            @exec("rm -r ".$tmpDir);
            if (!file_exists($file)) {
                return array(
                    'code' => 406,
                    'message' => '打包失败',
                );
            }

            return $file;
        } else {
            return $list;
        }
    }

    /**
     * 批量下载
     *
     * @param array $params
     *
     * @return array|string
     */
    public function manyDownRecord(array $params)
    {
        $list = $this->getRecordListFromElasticsearch($params);

        $file = '/tmp/'.date("YmdHis").$params['vcc_code'].'.lst';
        if (isset($list['code']) && $list['code'] == 200) {
            if (empty($list['data'])) {
                return array('code' => '407', 'message' => '没有数据');
            }
            foreach ($list['data'] as $data) {
                $recordAddress = isset($data['record_file']) ? $data['record_file'] : '';
                if (empty($recordAddress)) {
                    return array('code' => 401, 'message' => '路径不存在');
                }
                $recordPrefixs = $this->container->getParameter('record_prefix');
                $prefix = '';
                foreach ($recordPrefixs as $k => $r) {
                    if (strpos($recordAddress, $k) === 0) {
                        $prefix = $r;
                        $recordAddress = str_replace($k, '', $recordAddress);
                        break;
                    }
                }
                if (empty($prefix)) {
                    return array('code' => 402, 'message' => '路径不存在');
                }
                $mark = 'call';//标记是
                $baseUrl = $this->container->getParameter('record_oss_url');
                $url = $baseUrl.DIRECTORY_SEPARATOR.$prefix.DIRECTORY_SEPARATOR.$mark.DIRECTORY_SEPARATOR.$recordAddress;
                $url = str_replace('\\', '/', $url);
                file_put_contents($file, $url.PHP_EOL, FILE_APPEND);
            }
        }

        return array('code' => 200, 'url' => $file);
    }

    protected function readRemoteFile($url)
    {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $contents = curl_exec($ch);
        curl_close($ch);

        return $contents;
    }

    protected function processRecordUrl($recordUrl, $flag = 2)
    {
        if (empty($recordUrl)) {
            return false;
        }

        $recordPrefixs = $this->container->getParameter('record_prefix');
        $prefix = '';
        foreach ($recordPrefixs as $k => $r) {
            if (strpos($recordUrl, $k) === 0) {
                $prefix = $r;
                $recordUrl = str_replace($k, '', $recordUrl);
                break;
            }
        }

        if (empty($prefix)) {
            return false;
        }
        $mark = $flag == 1 ? 'voicemail' : 'call';
        $baseUrl = $this->container->getParameter('record_oss_url');
        $url = $baseUrl.DIRECTORY_SEPARATOR.$prefix.DIRECTORY_SEPARATOR.$mark.DIRECTORY_SEPARATOR.$recordUrl;
        $url = str_replace('\\', '/', $url);

        return $url;
    }

    /**
     * 获取留言，语音地址；
     *
     * @param array $param
     *
     * @return array|string
     */
    public function getSoundInfo(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $id = empty($param['id']) ? 0 : $param['id'];
        $callid = empty($param['callid']) ? 0 : $param['callid'];
        $agCdrid = empty($param['agcdr_id']) ? 0 : $param['agcdr_id'];
        $flag = empty($param['flag']) ? 0 : $param['flag'];
        $remark = empty($param['remark']) ? 1 : $param['remark'];
        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        if ($flag == 1) {
            $select = 'rec_file';
            $table = 'win_voicemail';//留言表
            $updateStr = $remark == 1 ? array('listen_mark' => 1) : array('down_mark' => 1);
            $this->dbal->update($table, $updateStr, array('id' => $id, 'vcc_id' => $vid));
        } else {
            $select = 'record_file';
            $table = 'win_agcdr';
        }

        if (!empty($id)) {
            $data = $this->dbal->fetchAssoc(
                "SELECT $select as address
                FROM $table WHERE id = :id",
                array('id' => $id)
            );
        } elseif (!empty($callid)) {
            $sql = "SELECT $select as address FROM $table WHERE call_id = :call_id AND record_mark=1 ";
            $condition = array('call_id' => $callid);
            if (!empty($agCdrid) && $flag != 1) {
                $sql .= " AND agcdr_id = :agcdr_id ";
                $condition['agcdr_id'] = $agCdrid;
            }
            $data = $this->dbal->fetchAssoc(
                $sql,
                $condition
            );
        } else {
            $data = array();
        }

        return $data;
    }

    /**
     * 播放录音
     *
     * @param array $params
     *
     * @return array|string
     */
    public function playRecord(array $params = array())
    {
        $vccCode = empty($params['vcc_code']) ? 0 : $params['vcc_code'];
        $callId = empty($params['call_id']) ? 0 : $params['call_id'];
        $agId = empty($params['ag_id']) ? '' : $params['ag_id'];

        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($callId)) {
            $ret = array(
                'code' => 403,
                'message' => 'call_id为空',
            );

            return $ret;
        }
        /*if (!is_numeric($callId)) {
            $ret = array(
                'code' => 404,
                'message' => 'call_id格式不对，要求为数字',
            );
            return $ret;
        }*/
        $where = "vcc_id=:vcc_id AND call_id=:call_id AND record_mark=1";
        $param = array('vcc_id' => $vccId, 'call_id' => $callId);
        if ($agId) {
            $where .= " AND ag_id = :ag_id ";
            $param['ag_id'] = $agId;
        }
        $recordFile = $this->dbal->fetchColumn(
            'SELECT record_file FROM win_agcdr
            WHERE '.$where.' LIMIT 1',
            $param
        );

        if (empty($recordFile) || !file_exists($recordFile)) {
            $ret = array(
                'code' => 405,
                'message' => '录音文件不存在',
            );

            return $ret;
        }

        return array('code' => '200', 'file' => $recordFile);
    }

    /**
     * 播放留言
     *
     * @param array $param
     *
     * @return array|string
     */
    public function playVoice(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $callId = empty($param['call_id']) ? 0 : $param['call_id'];
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        if (empty($callId)) {
            $ret = array(
                'code' => 403,
                'message' => 'call_id为空',
            );

            return $ret;
        }
        /*if (!is_numeric($callId)) {
            $ret = array(
                'code' => 404,
                'message' => 'call_id格式不对，要求为数字',
            );
            return $ret;
        }*/

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $where = "vcc_id=:vcc_id AND call_id=:call_id";
        $param = array('vcc_id' => $vccId, 'call_id' => $callId);
        $recordFile = $conn->fetchColumn(
            'SELECT rec_file FROM win_voicemail
            WHERE '.$where.' LIMIT 1',
            $param
        );

        if (empty($recordFile) || !file_exists($recordFile)) {
            $ret = array(
                'code' => 405,
                'message' => '录音文件不存在',
            );

            return $ret;
        }

        return array('code' => '200', 'file' => $recordFile);
    }

    /**
     * 新的播放录音
     *
     * @param array $params
     *
     * @return array|string
     */
    public function newPlayRecord(array $params = array())
    {
        $vccCode = empty($params['vcc_code']) ? 0 : $params['vcc_code'];
        $callId = empty($params['call_id']) ? 0 : $params['call_id'];
        $agId = empty($params['ag_id']) ? '' : $params['ag_id'];

        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($callId)) {
            $ret = array(
                'code' => 403,
                'message' => 'call_id为空',
            );

            return $ret;
        }
        /*if (!is_numeric($callId)) {
            $ret = array(
                'code' => 404,
                'message' => 'call_id格式不对，要求为数字',
            );
            return $ret;
        }*/
        $where = "vcc_id=:vcc_id AND call_id=:call_id AND record_mark=1";
        $param = array('vcc_id' => $vccId, 'call_id' => $callId);
        if ($agId) {
            $where .= " AND ag_id = :ag_id ";
            $param['ag_id'] = $agId;
        }
        $recordAddress = $this->dbal->fetchColumn(
            'SELECT record_file FROM win_agcdr
            WHERE '.$where.' LIMIT 1',
            $param
        );

        if (empty($recordAddress)) {
            $ret = array(
                'code' => 407,
                'message' => '录音不存在',
            );

            return $ret;
        }
        $recordPrefixs = $this->container->getParameter('record_prefix');
        $prefix = '';
        foreach ($recordPrefixs as $k => $r) {
            if (strpos($recordAddress, $k) === 0) {
                $prefix = $r;
                $recordAddress = str_replace($k, '', $recordAddress);
                break;
            }
        }

        if (empty($prefix)) {
            $ret = array(
                'code' => 406,
                'message' => '录音前缀不存在',
            );

            return $ret;
        }
        $baseUrl = $this->container->getParameter('record_oss_url');
        $url = $baseUrl.DIRECTORY_SEPARATOR.$prefix.DIRECTORY_SEPARATOR.'call'.DIRECTORY_SEPARATOR.$recordAddress;

        return array('code' => '200', 'file' => $url);
    }

    /**
     * 录音备份数据
     * @param array $param
     * @return array
     */
    public function getRecordBackupData(array $param = array())
    {
        $vccId = isset($param['vcc_id']) ? $param['vcc_id'] : '';
        $page = isset($param['page']) ? $param['page'] : 1;
        $rows = isset($param['rows']) ? $param['rows'] : 10;
        $order = isset($param['order']) ? $param['order'] : 'desc';
        $field = isset($param['field']) ? $param['field'] : 'record_date';
        $startTime = isset($param['startTime']) ? $param['startTime'] : '';
        $endTime = isset($param['endTime']) ? $param['endTime'] : '';
        if (empty($vccId)) {
            return array('code'=>402, 'message'=>'企业ID不能为空');
        }
        $where = " vcc_id='".$vccId."'";
        if (!empty($startTime)) {
            $where .= " AND record_date >= '$startTime' ";
        }
        if (!empty($endTime)) {
            $where .= " AND record_date <= '$endTime' ";
        }
        $start = $rows * $page - $rows;
        $start = $start > 0 ? $start : 0;

        try {
            $count = $this->dbal->fetchColumn("SELECT COUNT(*) FROM win_record_download_log WHERE $where");
            $data = $this->dbal->fetchAll(
                "SELECT id,vcc_id,record_date,num,file_size,expire_time,submit_time,staus,handle_start_time,handle_end_time
                FROM win_record_download_log
                WHERE {$where}
                ORDER BY {$field} {$order}
                LIMIT {$start},{$rows}"
            );
        } catch (\Exception $e) {
            $logger = $this->container->get('logger');
            $logger->error($e->getMessage());

            return array('code'=>400, 'message'=>'数据库执行错误');
        }
        foreach ($data as $key => $val) {
            if (empty($val['handle_end_time'])) {
                $data[$key]['handle_end_time'] = '';
            }
            if (empty($val['handle_start_time'])) {
                $data[$key]['handle_start_time'] = '';
            }
            if (empty($val['submit_time'])) {
                $data[$key]['submit_time'] = '';
            }
            $data[$key]['staus_translation'] = $this->recordbatchcreat[$val['staus']];
            $data[$key]['file_size'] = sprintf("%.2f", $data[$key]['file_size'] / 1024);
            if ($val['staus'] == 3) {
                $downloadUrl = $this->container->getParameter('download_record_url').'?vcc_id='.$vccId.'&id='.$val['id'].'&sign=';
                $data[$key]['download_url'] = $downloadUrl.md5($val['id'].$vccId.$val['submit_time'].$val['file_size']);
            }
        }

        return array(
            'code'=>200,
            'message'=>'success',
            'records' => $count,
            'page' => $page,
            'total' => ceil($count/$rows),
            'rows'=>$data,
        );
    }

    /**
     * 创建录音备份任务
     * @param array $param
     * @return array
     */
    public function creatRecordBackup(array $param = array())
    {
        $vccId = isset($param['vcc_id']) ? $param['vcc_id'] : '';
        $startTime = isset($param['startTime']) ? $param['startTime'] : '';
        $endTime = isset($param['endTime']) ? $param['endTime'] : '';
        $haved = array();   //已经存在的任务
        $havedNum = 0;  //存在的任务个数
        $newWork = 0; //新的任务个数
        $noWork = 0; //未处理的任务

        if (empty($vccId)) {
            return array('code'=>400, 'message'=>'企业ID不能为空');
        }

        if (!empty($startTime) && !empty($endTime)) {
            if (strtotime($startTime) > strtotime($endTime)) {
                return array('code'=>401, 'message'=>'时间参数不正确');
            }
            if (strtotime($endTime) - strtotime($startTime) > 2592000) {
                return array('code'=>402, 'message'=>'一次最多可以备份31天的录音文件');
            }
        } else {
            return array('code'=>403, 'message'=>'缺少备份时间段');
        }
        $data['vcc_id'] = $vccId;
        try {
            $count = $this->dbal->fetchColumn("SELECT COUNT(*) FROM win_record_download_log WHERE staus in(1,2) and vcc_id=$vccId");
            //获取开始到结束时间段的每一天
            for ($i=0; strtotime($startTime.'+'.$i.' days') <= strtotime($endTime) && $i < 365; $i++) {
                $time = strtotime($startTime.'+'.$i.' days');
                $data['record_date'] = date('Y-m-d', $time);
                $data['submit_time'] = time();
                $haveing = $this->dbal->fetchColumn("SELECT COUNT(*) FROM win_record_download_log WHERE vcc_id=$vccId and record_date='".$data['record_date']."'");
                if ($haveing > 0) {
                    $haved[] = $haveing;
                    $havedNum++;
                } else {
                    if ($newWork + $count >= 31) {
                        $noWork++;
                        continue;
                    } else {
                        $this->dbal->insert('win_record_download_log', $data);
                        $newWork++;
                    }
                }
            }
        } catch (\Exception $e) {
            $logger = $this->container->get('logger');
            $logger->error($e->getMessage());

            return array('code'=>405, 'message'=>'数据库执行错误');
        }
        if ($newWork == 0) {
            if ($noWork > 0) {
                return array('code'=>406, 'message'=>'任务超出上线');
            } else {
                return array('code'=>407, 'message'=>'备份文件已经存在');
            }
        };
        if ($noWork > 0) {
            return array('code'=>200, 'message'=>sprintf('成功创建%s个，有%s个已经存在，超出%s个', $newWork, $havedNum, $noWork));
        }
        if ($havedNum > 0) {
            return array('code'=>200, 'message'=>sprintf('成功创建%s个，有%s个已经存在', $newWork, $havedNum));
        }

        return array('code'=>200, 'message'=>sprintf('成功创建%s个任务', $newWork));
    }
}
